<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/8/31
 * Time: 13:17
 */

namespace app\common\model;


use app\common\utils\DateTimeUtil;
use think\Db;
use think\Model;

/**
 * Class AgencySalesman
 * @package app\common\model
 *
 * @property integer id
 * @property integer userid
 * @property integer agency_id
 * @property string code
 * @property string mobile
 * @property string realname
 * @property integer agency_role
 * @property string created
 * @property boolean valid
 *
 * @todo v1.4.1废弃
 */
class AgencySalesman extends Model
{
    protected $table = 'agency_salesman';
    protected $pk = 'id';

    /**
     * 生成推广码，最大+1
     *
     * @return string
     *
     * @todo v1.4.1废弃
     */
    public static function generateCode() {
        $sql = <<<SQL
SELECT max(cast(code AS INTEGER)) AS code FROM agency_salesman
SQL;
        $re = Db::query($sql);
        $code = intval($re[0]['code'] ?? 0) + 1;

        return sprintf('%04d', $code);
    }

    /**
     * 创建默认推广信息
     *
     * @param $uid
     * @param bool $reload
     * @return mixed|null
     *
     * @todo v1.4.1废弃
     */
    public static function createDefault($uid, $reload = false) {

        $re = self::get(['userid' => $uid]);
        if ($re) return $re->toArray();

        $model = self::create([
            'userid' => $uid,
            'agency_id' => 0,
            'code' => self::generateCode(),
        ]);
        if ($reload) return self::agencyInfo($uid);
        else return $model->toArray();
    }

    public static function getByCode(string $code) {
        return self::get(['code' => $code]);
    }

    /**
     * 我的推广信息，基本信息
     *
     * @param int $uid
     * @return mixed|null
     *
     * @todo v1.4.1废弃
     */
    public static function agencyInfo(int $uid) {

        $sql = <<<SQL
SELECT u.id uid,s.code agency_code,s.accumulated_bill_amount,s.id salesman_id,
 u.nickname,u.mobile,a.name agency_name, a.salesman_profit_rate * a.profit_rate AS profit_rate
FROM agency_salesman s
JOIN users u ON s.userid = u.id
JOIN agency a ON s.agency_id = a.id
WHERE s.userid=:uid
SQL;
        $info = Db::query($sql, ['uid' => $uid,]);
        $info = $info[0] ?? null;
        if (empty($info)) return null;

        if (empty($info['nickname'])) {
            $info['nickname'] = mobile_hidden($info['mobile']);
        }
        $info['invite_url'] = self::getInviteUrl($info['agency_code']);

        $info['profit_rate'] = round($info['profit_rate'],2);

        return $info;
    }

    public static function getInviteUrl($code) {
        return config('server.host').'/site/share/invite_page?invite_code='.$code;
    }

    /**
     * v1.0
     *
     * @param int $uid
     * @param int $rows
     * @param int $page
     * @param bool $pageTotal
     * @return mixed
     *
     * @todo v1.4.1废弃
     */
    public static function myInvitedUsers(int $uid, int $rows = 10, int $page = 1, $pageTotal = false) {

        $query = Db::table('users u');
        $query->join('agency_invite_user aiu','aiu.userid = u.id');
        $query->join('agency_salesman s','s.id = aiu.salesman_id');
        $query->where('s.userid','=',$uid);
        $query->field('u.id uid, u.mobile, u.regtime');


        if ($pageTotal) {
            $queryMonthNum = clone $query;
            $queryMonthNum->where('aiu.created','>', date('Y-m-').'01');
            $monthNum = $queryMonthNum->count();
            $pager = $query->paginate($rows,false, ['page' => $page]);
            $list = $pager->items();
            $total = $pager->total();
        } else {
            $query->page($page,$rows);
            $list = $query->select();
            $total = null;
            $monthNum = null;
        }

        foreach ($list as & $item) {
            $item['regtime'] = date('Y-m-d', $item['regtime']);
        }

        return ['list' => $list, 'total' => $total, 'month_total' => $monthNum];
    }

    /**
     * v1.2
     * 我推广的用户列表
     *
     * @param $salesman_id
     * @param $rows
     * @param $page
     * @param array|null $timeRange
     * @param bool $totalPage
     * @return array
     * @internal param null $month
     *
     * @todo v1.4.1废弃
     */
    public static function listInvitedUser($salesman_id, $rows, $page, array $timeRange = null, $totalPage = false) {
        $query = Db::table('users u');
        $query->join('agency_invite_user aiu','aiu.userid = u.id');
        $query->where('aiu.salesman_id','=',$salesman_id);
        $query->where('aiu.valid','=','true');
        $query->where('expired_time','>', time());
        if (!is_null($timeRange)) {
            $query->whereBetween('u.regtime', $timeRange);
        }
        $query->field('u.id uid, u.mobile, u.regtime');
        $paginate = $query->paginate($rows,!$totalPage, ['page'=>$page]);

        $list = $paginate->items();
        foreach ($list as & $item) {
            $item['regtime'] = date('Y-m-d H:i', $item['regtime']);
            $item['mobile'] = mobile_hidden($item['mobile']);
        }

        return ['list' => $list, 'total' => $paginate->total(), 'lastPage' => $paginate->lastPage()];
    }

    /**
     * v1.2
     * 我的推广用户统计人数
     *
     * @param $salesman_id
     * @param array|null $timeRange
     * @return int|string
     *
     * @todo v1.4.1废弃
     */
    public static function countInvitedUser($salesman_id, array $timeRange = null) {
        $query = Db::table('users u');
        $query->join('agency_invite_user aiu','aiu.userid = u.id');
        $query->where('aiu.salesman_id','=',$salesman_id);
        $query->where('aiu.valid','=','true');
        $query->where('expired_time','>', time());
        if (!is_null($timeRange)) {
            $query->whereBetween('u.regtime', $timeRange);
        }
        return $query->count();
    }

    /**
     * 我的推广订单
     *
     * @param $salesman_id
     * @param $rows
     * @param $page
     * @param array|null $timeRange
     * @return false|array
     *
     * @todo v1.4.1废弃
     */
    public static function bills($salesman_id, $rows, $page, array $timeRange = null) {
        $query = Db::table('buy_bill b');
        $query->join('users u','u.id=b.bill_user');
        $query->join('agency_bill ab','ab.bill_id=b.bill_id');
        $query->where('ab.salesman_id','=',$salesman_id);
        $query->where('bill_type in (1,3)');
        if ($timeRange) $query->whereBetween('b.bill_paytime',$timeRange);
        $query->where('b.bill_have_paid=true');
        $query->field('
            b.bill_id,
            b.bill_item_title as title,
            b.bill_paytime as pay_time,
            b.bill_pay_amount as pay_amount,
            u.mobile as customer
        ');
        $query->page($page, $rows);
        $list = $query->select();

        foreach ($list as & $item) {
            $item['pay_time'] = DateTimeUtil::format($item['pay_time']);
            $item['customer'] = mobile_hidden($item['customer']);
            $item['pay_amount'] = round($item['pay_amount'],2);
        }

        return $list;
    }

    /**
     * 统计订单总金额
     *
     * @param $salesman_id
     * @param array|null $timeRange
     * @return float|int
     *
     * @todo v1.4.1废弃
     */
    public static function billTotalAmount($salesman_id, array $timeRange = null) {
        $query = Db::table('buy_bill b');
        $query->join('agency_bill ab','ab.bill_id=b.bill_id');
        $query->where('ab.salesman_id','=',$salesman_id);
        if ($timeRange) $query->whereBetween('b.bill_paytime',$timeRange);
        $query->where('b.bill_have_paid=true');
        $sum = $query->sum('bill_pay_amount');

        return strval(round($sum,2));
    }

}